package com.hmjk.health.views;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

import android.content.Context;
import android.text.InputType;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.EditText;

public class GlucoseEdit extends EditText{
	private String STAG = GlucoseEdit.class.getSimpleName();
	private int unit = -1;
	private float value = 0.0f;
	private DecimalFormat mmolDf;
	private float ref = 0.0f;
	private String TAG = null;
			
	public GlucoseEdit(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
		// TODO Auto-generated constructor stub
	}
	
	public GlucoseEdit(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
		// TODO Auto-generated constructor stub
	}
	
	public GlucoseEdit(Context context) {
		super(context);
		init();
		// TODO Auto-generated constructor stub
	}
	
	public void setUserTag(String tag){
		TAG = tag;
	}
	
	private void logd(String info){
		if(TAG != null){
			Log.d(STAG+":"+TAG,info);
		}
	}
	
	private void init(){
		mmolDf = new DecimalFormat("0.0");
		mmolDf.setRoundingMode(RoundingMode.HALF_UP);

	}
	
	public void setReference(float r){
		ref = r;
	}
	
	public void setUnit(int u){
		unit = u;
		if(unit == 0){
			setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
		}else{
			setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
		}
	}
	
	public void setMMOL(float f){
		logd("setMMOL value = " + f);
		value = f;
		if(unit == 0){
			String s = String.valueOf((int)(value * 18));
			setText(s);
			setSelection(s.length());
			logd("setMMOL show = " + s);
		}else{
			String s = mmolDf.format(value);
			setText(s);
			setSelection(s.length());
			logd("setMMOL show = " + s);
		}
	}
	
	public float getMMOL(){
		String s = getText().toString().trim();
		logd("getMMOL string = " + s);
		
		if((s == null) || s.trim().isEmpty()){
			value = ref;
			setMMOL(value);
		}
		
		if(unit == 0){
			try{
				float mg= Float.parseFloat(s);
				BigDecimal bd = new BigDecimal(mg/18);
				bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP); 
				value = bd.floatValue();
			}catch(NumberFormatException e){
				value = ref;
				setMMOL(value);
			}
		}else{
			try{
				float mmol= Float.parseFloat(s);
				BigDecimal bd = new BigDecimal(mmol);
				bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP); 
				value = bd.floatValue();
			}catch(NumberFormatException e){
				value = ref;
				setMMOL(value);
			}
		}
		logd("getMMOL value = " + value);
		return value;
	}

}
